//
//  ConsumerCreatController.m
//  XiaoMiao
//
//  Created by kinglian_iOS_000 on 2018/1/23.
//  Copyright © 2018年 smallyou. All rights reserved.
//

#import "ConsumerCreatController.h"
#import "BRPickerView.h"
#import "AddressProvinceCityController.h"
#import "ProjectSeletedController.h"
#import "XMCameraAngleModel.h"
#import "XMUploadPhotoModel.h"
#import "SuccessToOriginController.h"

#import "LocationManager.h"

#import "XMCameraTimeAndAngleViewController.h"

@interface ConsumerCreatController () <UIActionSheetDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *sexTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *ageTextField;
@property (weak, nonatomic) IBOutlet UITextField *locationTextField;

@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIView *sexView;
@property (weak, nonatomic) IBOutlet UIView *ageView;
@property (weak, nonatomic) IBOutlet UIView *locationView;

@property (weak, nonatomic) IBOutlet UIButton *nextStepButton;

/** <#属性#> */
@property (nonatomic, copy) NSString *imageServerPath;

/**datas*/
@property(nonatomic,strong) NSMutableArray <XMCameraAngleModel *>*cameraAngleModels;
/**XMUploadPhotoModel*/
@property(nonatomic,strong) XMUploadPhotoModel *uploadPhotoModel;
@end

@implementation ConsumerCreatController

- (void)setUpCameraAngleModels:(NSMutableArray <XMCameraAngleModel *>*)cameraAngleModels
              uploadPhotoModel:(XMUploadPhotoModel *)uploadPhotoModel
{
    self.cameraAngleModels = cameraAngleModels;
    self.uploadPhotoModel = uploadPhotoModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"新建用户";
    
    self.headImageView.layer.cornerRadius = 18.f;
    self.headImageView.layer.masksToBounds = YES;
     
    NSArray *tapViews = @[self.headView, self.sexView, self.ageView, self.locationView];
    for (UIView *tapView in tapViews) {
        [tapView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapViewDidTap:)]];
    }
    
    [self.nextStepButton addTarget:self action:@selector(btnDidClick:) forControlEvents:UIControlEventTouchUpInside];
    
    WEAKSELF
    [[LocationManager manager] startLocationLocationBlock:^(NSString *province, NSString *city) {
        weakSelf.locationTextField.text = [NSString stringWithFormat:@"%@ %@", province, city];
    }];
}

#pragma mark - Action
- (void)tapViewDidTap:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
    
    UIView *tapView = tap.view;
    
    if (tapView == self.sexView) {
        [self p_showSexPicker];
    }else if (tapView == self.ageView) {
        [self p_showAgePicker];
    }else if (tapView == self.locationView) {
        [self p_showLocationList];
    }else if (tapView == self.headView) {
        [self p_showAddHeadImage];
    }
}

- (void)btnDidClick:(UIButton *)sender {
     if (sender != self.nextStepButton) {
         return;
     }
    
    // 请求参数
    NSString *msg = [self p_valiteIsCanCreatUser];
    if (msg.length != 0) {
        [self.view endEditing:YES];
        [KLProgressHUD showPromptHUDWithMessage:msg];
        return;
    }
    
    NSString *age = nil;
    if (self.ageTextField.text.length != 0) {
        age = [self.ageTextField.text substringWithRange:NSMakeRange(0, self.ageTextField.text.length - 1)];
    }
    
    NSArray *locationArray = [self.locationTextField.text componentsSeparatedByString:@" "];
    NSString *province = nil;
    NSString *city = nil;
    if (locationArray.count == 2) {
        province = locationArray[0];
        city = locationArray[1];
    }
    
    BaseInfoModel *infoModel =
    [BaseInfoModel modelWithProfile:self.imageServerPath
                           realName:self.nameTextField.text
                                sex:self.sexTextField.text
                                age:age
                               prix:@"86"
                              phone:self.phoneTextField.text
                           province:province
                               city:city];
    
    //
//    if (self.cameraAngleModels.count != 0 || self.uploadPhotoModel) { // 拍照新建用户
//        self.uploadPhotoModel.baseInfoModel = infoModel;
//
//        [self request_uploadCameraImage];
    
//    }else { // 客户列表-新建用户
//        ProjectSeletedController *project = [[ProjectSeletedController alloc] initNewListWithBaseInfoModel:infoModel];
    
    XMCameraTimeAndAngleViewController * vc = [[XMCameraTimeAndAngleViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
//    }
}

#pragma mark - Private
- (NSString *)p_valiteIsCanCreatUser {
//    if (self.headImageView.image == kDefaultPlaceholdeImage) {
//        return @"请上传头像";
//    }
//    if (self.headImageView.image != kDefaultPlaceholdeImage && self.imageServerPath.length == 0) {
//        return @"请重新选择上传头像";
//    }
    if ([NSString app_isBlankString:self.nameTextField.text]) {
        return @"请输入姓名";
    }
//    if (self.nameTextField.text.length >= 10) {
//        return @"姓名太长了！";
//    }
//    if (![AppGlobal isMatchingMobile:self.phoneTextField.text]) {
//        return @"请输入正确的手机号";
//    }
    if ([NSString app_isBlankString:self.sexTextField.text]) {
        return @"请选择性别";
    }
//    if ([NSString app_isBlankString:self.ageTextField.text]) {
//        return @"请选择年龄";
//    }
//    if ([NSString app_isBlankString:self.locationTextField.text]) {
//        return @"请选择所在地";
//    }
    
    return nil;
}

- (void)p_showSexPicker {
    WEAKSELF
    [BRStringPickerView showStringPickerWithTitle:nil dataSource:kSexArray defaultSelValue:self.sexTextField.text resultBlock:^(id selectValue) {
        
        if ([NSString app_isBlankString:weakSelf.sexTextField.text] && [NSString app_isBlankString:selectValue]) {
            weakSelf.sexTextField.text = kSexArray[0];
        }else {
            weakSelf.sexTextField.text = selectValue;
        }
    }];
}

- (void)p_showAgePicker {
    WEAKSELF
    [BRStringPickerView showStringPickerWithTitle:nil dataSource:kAgeArray defaultSelValue:self.ageTextField.text resultBlock:^(id selectValue) {
        
        if ([NSString app_isBlankString:weakSelf.ageTextField.text] && [NSString app_isBlankString:selectValue]) {
            weakSelf.ageTextField.text = kAgeArray[0];
        }else {
            weakSelf.ageTextField.text = selectValue;
        }
    }];
}

- (void)p_showLocationList {
    AddressProvinceCityController *address = [[AddressProvinceCityController alloc] initWithAddressVCType:AddressVCTypeProvince parentId:@"" titleName:@""];
    [self.navigationController pushViewController:address animated:YES];
    
    WEAKSELF
    [address setAddressCompleted:^(NSString *province, NSString *city) {
        weakSelf.locationTextField.text = [NSString stringWithFormat:@"%@ %@", province, city];
    }];
}

- (void)p_showAddHeadImage {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择相片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    
    [actionSheet showInView:self.view];
}

#pragma mark - Request
- (void)request_uploadHeadImage {
    WEAKSELF
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"上传头像.."];
    [AppHttpClient userModule_uploadImage:self.headImageView.image completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
        progressHUD.hidden = YES;
        if (success) {
            weakSelf.imageServerPath = imageUrl;
        }else {
            [KLProgressHUD showErrorHUDWithMessage:errorMsg];
        }
    }];
}

//上传照片获取路径
- (void)request_uploadCameraImage
{
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"上传照片.."];
    
    //获取图片并上传
    dispatch_group_t group = dispatch_group_create();
    for (XMCameraAngleModel *angle in self.cameraAngleModels) {
        if (angle.photoed && (angle.resultImageUrl.length == 0)) {
            //取出图片
            UIImage *image = angle.resultImage;
            //上传图片
            dispatch_group_enter(group);
            
            [AppHttpClient userModule_uploadImage:image completion:^(BOOL success, NSString *imageUrl, NSString *errorMsg) {
                if (success) {
                    NSLog(@"----->上传成功");
                    angle.resultImageUrl = imageUrl;
                }
                
                dispatch_group_leave(group);
            }];
        }
    }
    
    WEAKSELF
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        progressHUD.hidden = YES;
        
        NSMutableArray <NSMutableDictionary *>*arrayM = [NSMutableArray array];
        for (XMCameraAngleModel *angle in self.cameraAngleModels) {
            if (angle.resultImageUrl.length && angle.photoed) {
                NSMutableDictionary *dict = [NSMutableDictionary dictionary];
                dict[@"imageUrl"] = angle.resultImageUrl;
                dict[@"templeId"] = angle.Id;
                [arrayM addObject:dict];
            }
        }
        
        NSError *error;
        NSData *date = [NSJSONSerialization dataWithJSONObject:arrayM options:NSJSONWritingPrettyPrinted error:&error];
        if (error) {
            NSLog(@"转换error：%@", error);
        }
        NSString *jsonStr = [[NSString alloc] initWithData:date encoding:NSUTF8StringEncoding];
        
        //完善上传模型
        weakSelf.uploadPhotoModel.photographUserAngleJson = jsonStr;
        
        //跳转到下一级
        [self request_photoAndInfo];
    });
}

// 保存照片和资料请求
- (void)request_photoAndInfo
{
    KLProgressHUD *progressHUD = [KLProgressHUD showWaitingHUDWithSuperView:self.view message:@"保存中.."];
    
    WEAKSELF
    [AppNetwork album_uploadPhotoAndInfoWithModel:self.uploadPhotoModel completion:^(BOOL success, NSString *errorMsg) {
        progressHUD.hidden = YES;
        
        if (!success) {
            [KLProgressHUD showErrorHUDWithMessage:errorMsg];
            return;
        }
        
        [KLProgressHUD showSuccessHUDWithSuperView:nil message:@"上传成功" isHudEnable:YES completed:^{
            SuccessToOriginController *success = [[SuccessToOriginController alloc] init];
            [success setNavTitle:@"新建完成" desTitle:@"新建完成" btnTitle:@"返回查询"];
            [weakSelf.navigationController pushViewController:success animated:YES];
            
            [success setBtnClickHandle:^(SuccessToOriginController *btnVC) {
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            }];
        }];
    }];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (0 == buttonIndex) { // 打开相机
        if (![AppGlobal isCameraDeviceAvalable]) {
            return;
        }
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    } else if (1 == buttonIndex) { // 打开照片库
        if (![AppGlobal isAssetsLibraryAvalable]) {
            return;
        }
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.navigationBar.translucent = NO;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        self.headImageView.image = image;
        self.imageServerPath = nil;
        
        [self request_uploadHeadImage];
    }];
}

@end
